// pages/cmt/cmt.js
Page({
  transformTime(timestamp = +new Date()) {
   const  addZero =  (m) =>{
      return m < 10 ? '0' + m : m;
    }
    if (timestamp) {
        var time = new Date(timestamp);
        var y = time.getFullYear();
        var M = time.getMonth() + 1;
        var d = time.getDate();
        var h = time.getHours();
        var m = time.getMinutes();
        var s = time.getSeconds();
        return y + '-' + addZero(M) + '-' + addZero(d) + ' ' + addZero(h) + ':' + addZero(m) + ':' + addZero(s);
      } else {
          return '';
      }
},

 
    /**
     * 页面的初始数据
     */
    data: {
      showForm:false,
      stars: [1, 2, 3, 4, 5],
      selectedStar: 4,
      comment: '',
siteId:'',
list:'',
info:{}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
const siteId = options.siteid
this.setData({
  siteId
})
this.getCmtList()
    },
    rate: function(e) {
      const index = e.currentTarget.dataset.value;
      console.log(index)
      this.setData({
        selectedStar: index + 1
      });
    },
    inputComment: function(e) {
      this.setData({
        comment: e.detail.value
      });
    },
  async   getCmtList(){
const res = await wx.cloud.database().collection('cmt').where({
  siteId:this.data.siteId
}).orderBy('created_at', 'desc').get()
console.log(res)
res.data.forEach(i=>{
  i.time = this.transformTime(i.created_at)
})
this.setData({
  list:res.data
})
    },
    addCmt(){
this.setData({
  showForm:true
})
    },
    sendIt(){
const datas = {
  siteId:this.data.siteId,
  stars:this.data.selectedStar,
  userNickName:wx.getStorageSync('userInfo').nicKName,
  userAvatarUrl:wx.getStorageSync('userInfo').awatarUrl,
  content:this.data.comment,
  created_at:new Date().getTime()
}
wx.cloud.database().collection('cmt').add({
  data:datas
}).then(r=>{
  wx.showToast({
    title: '发表成功',
  })
  this.getCmtList()
  this.setData({
    showForm:false
  })
})
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})